<!--
 * @Description: 竣工收尾工作计划
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2022-01-20 11:29:21
 * @LastEditTime: 2023-07-07 15:37:14
 * @FilePath: \cscec-pms-admin\src\views\construction\constructionCompleted\constructionCompletedView.vue
-->
<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <a-spin :spinning="submiting">
      <a-card>
        <title-name title="竣工收尾工作计划" />
        <div class="btn-wrapper">
          <template v-if="!isAudit">
            <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.nodeType===1 || isDetail || loading"
              @click="taskTemplateVisible = true"
            >
              导入模板
            </a-button>
            <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.nodeType===1 || isDetail || loading"
              @click="handleCreateSiblingWorkPack"
            >
              新增同级阶段/类别
            </a-button>
            <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.nodeType === 1 || isDetail || loading"
              @click="handleCreateWorkPack"
            >
              新增下级阶段/类别
            </a-button>
            <a-button
              type="primary"
              :disabled="notSelectRow || isDetail || loading"
              @click="handleCreateWork"
            >
              新增业务事项
            </a-button>
            <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.nodeOrder === 0 || selectRow.nodeOrder === 2 || isDetail || loading"
              @click="handleMoveUp"
            >
              上移
            </a-button>
            <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.nodeOrder === 1 || selectRow.nodeOrder === 2 || isDetail || loading"
              @click="handleMoveDown"
            >
              下移
            </a-button>
            <!-- <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.level === 1 || selectRow.nodeType === 1 || isDetail || loading"
              @click="handleUpgradeWorkPack"
            >
              升级
            </a-button>
            <a-button
              type="primary"
              :disabled="notSelectRow || selectRow.nodeOrder === 0 || selectRow.nodeOrder === 2 || selectRow.nodeType === 1 || isDetail || loading"
              @click="handleDowngradeWorkPack"
            >
              降级
            </a-button> -->
            <a-button
              type="primary"
              :disabled="notSelectRow || isDetail || selectRow.isRootOneNode || loading"
              @click="handleRemove"
            >
              删除
            </a-button>
          </template>
          <a-button
            type="primary"
            :disabled="loading"
            @click="ganttVisible = true"
          >
            查看甘特图
          </a-button>
          <a-button
            type="primary"
            :disabled="loading"
            @click="allTreeExpansion"
          >
            展开全部
          </a-button>
          <a-button
            type="primary"
            :disabled="loading"
            @click="$refs.table.clearTreeExpand()"
          >
            收起全部
          </a-button>
          <a-button
            type="primary"
            :disabled="loading"
            @click="loadData"
          >
            手动刷新
          </a-button>
        </div>
        <upload-list
          :business-code="'PM41'"
          :edit-model="2"
          style="margin:5px 0;"
          :text="'上传双代号网络图'"
          :disabled="loading || isDetail"
          :show-upload.sync="showUpload"
          :upload-arrys.sync="fileList"
          :project-id="scheduleCompletionPlanId"
          :update-code="1"
          @fileArrysData="handleFileUploaded"
        />
        <div class="pub-table-select-count">
          <a-icon
            type="info-circle"
            theme="twoTone"
          />
          <span>
            项目：<span class="totalNum">{{ tableInfo.projectName }}</span>
          </span>
          <span>
            节点共 <span class="totalNum">{{ tableInfo.nodeTotalNum }}</span> 项
          </span>
          <span>
            一级节点共 <span
              class="totalNum"
              @click="handleNodeInfo(1)"
            >{{ tableInfo.firstNodeNum }}</span> 项
          </span>
          <span>
            二级节点共 <span
              class="totalNum"
              @click="handleNodeInfo(2)"
            >{{ tableInfo.secondNodeNum }}</span> 项
          </span>
          <span>
            三级节点共 <span
              class="totalNum"
              @click="handleNodeInfo(3)"
            >{{ tableInfo.threeNodeNum }}</span> 项
          </span>
          <span>
            周期天数 <span class="totalNum">{{ tableInfo.periodDay }}</span> 天
          </span>
          <span>
            周期间隔 <span class="totalNum">{{ tableInfo.periodDate }}</span>
          </span>
        </div>
        <a-spin :spinning="loading">
          <u-table
            ref="table"
            fixed-columns-roll
            :height="500"
            show-header-overflow
            :tree-config="{
              children: 'childTree',
              expandAll: false,
            }"
            row-id="id"
            :use-virtual="true"
            border
            class="construction-schedule-view-table"
            @row-click="handleRowClick"
          >
            <!-- :fixed="item.dataIndex === 'sortNum' || item.dataIndex === 'phaseCategory'" -->
            <u-table-column
              v-for="item in columns1"
              :key="item.dataIndex"
              :prop="item.dataIndex"
              :label="item.title"
              :width="item.width"
              :tree-node="item.dataIndex === 'phaseCategory'"
              align="center"
            >
              <template v-slot="{ row }">
                <!-- 查看 -->
                <span
                  v-if="isDetail"
                  :title="row[item.dataIndex]"
                  class="span-ellipsis"
                >
                  <template v-if="row.nodeType === 0">
                    <template v-if="['sortNum','phaseCategory','businessMatters','period','planStartTime','planEndTime'].includes(item.dataIndex)">
                      {{ row[item.dataIndex] }}
                    </template>
                  </template>
                  <template v-else>
                    <template v-if="item.dataIndex === 'controlLevelId'">
                      {{ row.controlLevelName }}
                    </template>
                    <template v-else-if="item.dataIndex === 'directResPerList'">
                      {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                    </template>
                    <a-switch
                      v-else-if="item.dataIndex === 'isKeyNode'"
                      v-model="row.isKeyNode"
                      checked-children="是"
                      un-checked-children="否"
                      disabled
                    />
                    <template v-else>
                      {{ row[item.dataIndex] }}
                    </template>
                  </template>
                </span>
                <!-- 查看 -->
                <!-- 编辑 -->
                <span
                  v-else
                  :title="row[item.dataIndex]"
                >
                  <!-- 阶段类别 -->
                  <span
                    v-if="row.nodeType === 0"
                    class="span-ellipsis"
                  >
                    <span v-if="['sortNum','businessMatters','period','planStartTime','planEndTime'].includes(item.dataIndex)">
                      {{ row[item.dataIndex] }}
                    </span>
                    <!-- 阶段/类别 -->
                    <BaseInput
                      v-if="item.dataIndex === 'phaseCategory'"
                      v-model="row.phaseCategory"
                      :placeholder="'请输入'+item.title"
                      @focus="saveFocusValue(item.dataIndex, row[item.dataIndex])"
                      @blur="handleUpdate(row, false, item.dataIndex)"
                    />
                    <!-- 阶段/类别 -->
                  </span>
                  <!-- 阶段类别 -->
                  <!-- 业务事项 -->
                  <template v-else>
                    <!-- 序号 -->
                    <span v-if="item.dataIndex === 'sortNum'">
                      {{ row[item.dataIndex] }}
                    </span>
                    <!-- 序号 -->
                    <!-- 业务事项 -->
                    <BaseInput
                      v-if="item.dataIndex === 'businessMatters'"
                      v-model="row.businessMatters"
                      :placeholder="'请输入'+item.title"
                      @focus="saveFocusValue(item.dataIndex, row[item.dataIndex])"
                      @blur="handleUpdate(row, false, item.dataIndex)"
                    />
                    <!-- 业务事项 -->
                    <!-- 管控级别 -->
                    <a-select
                      v-if="item.dataIndex === 'controlLevelId'"
                      v-model="row.controlLevelId"
                      :placeholder="'请选择'+item.title"
                      class="width-100"
                      @change="handleUpdate(row, false, item.dataIndex)"
                    >
                      <a-select-option
                        v-for="{value,label} in controlLevelList"
                        :key="value"
                        :value="value"
                      >
                        {{ label }}
                      </a-select-option>
                    </a-select>
                    <!-- 管控级别 -->
                    <!-- 周期(天) -->
                    <!-- <BaseInputNumber
                      v-if="item.dataIndex === 'period'"
                      v-model="row.period"
                      :placeholder="'请输入'+item.title"
                      :min="1"
                      :max="2000"
                      :is-int="true"
                      @blur="(e)=>{handleComputePeriod(e.target._value,row,0)}"
                    /> -->
                    <template v-if="item.dataIndex === 'period'">
                      {{ row[item.dataIndex] }}
                    </template>
                    <!-- 周期(天) -->
                    <!-- 计划开始时间 -->
                    <a-date-picker
                      v-if="item.dataIndex === 'planStartTime'"
                      v-model="row.planStartTime"
                      :allow-clear="false"
                      :placeholder="'请选择'+item.title"
                      :disabled-date="(current)=>{return planStartTimeDisabled(current,row)}"
                      :open="row.planStartTimeOpen"
                      @openChange="(e)=>{row.planStartTimeOpen = e}"
                      @change="(e)=>{handleComputePeriod(e,row,1)}"
                      @focus="saveFocusValue(item.dataIndex, row[item.dataIndex])"
                    />
                    <!-- 计划开始时间 -->
                    <!-- 计划完成时间 -->
                    <a-date-picker
                      v-if="item.dataIndex === 'planEndTime'"
                      v-model="row.planEndTime"
                      :allow-clear="false"
                      :placeholder="'请选择'+item.title"
                      :disabled-date="(current)=>{return planEndTimeDisabled(current,row)}"
                      :open="row.planEndTimeOpen"
                      @openChange="(e)=>{row.planEndTimeOpen = e}"
                      @change="(e)=>{handleComputePeriod(e,row,2)}"
                      @focus="saveFocusValue(item.dataIndex, row[item.dataIndex])"
                    />
                    <!-- 计划完成时间 -->
                    <!-- 前置任务 -->
                    <a
                      v-if="item.dataIndex === 'frontTask'"
                      class="span-ellipsis"
                      @click="handlePredecessorTask(row)"
                    >
                      <template v-if="!row.frontTask">
                        设置
                      </template>
                      <template v-else>
                        {{ row[item.dataIndex] }}
                      </template>
                    </a>
                    <!-- 前置任务 -->
                    <!-- 间隔时间 -->
                    <span
                      v-if="item.dataIndex === 'intervalTime'"
                      class="span-ellipsis"
                    >
                      {{ row[item.dataIndex] }}
                    </span>
                    <!-- 间隔时间 -->
                    <!-- 完成标准 -->
                    <a-auto-complete
                      v-if="item.dataIndex === 'completeStandard'"
                      v-model="row.completeStandard"
                      :placeholder="'请选择'+item.title"
                      :data-source="completeStandardList"
                      class="width-100"
                      allow-clear
                      :filter-option="true"
                      @change="handleCompleteStandard($event,row)"
                    />
                    <!-- 完成标准 -->
                    <!-- 验证资料 -->
                    <BaseInput
                      v-if="item.dataIndex === 'verifyFiles'"
                      v-model="row.verifyFiles"
                      :placeholder="'请输入'+item.title"
                      @focus="saveFocusValue(item.dataIndex, row[item.dataIndex])"
                      @blur="handleUpdate(row, false, item.dataIndex)"
                    />
                    <!-- 验证资料 -->
                    <!-- 第一责任人 -->
                    <span
                      v-if="item.dataIndex === 'firstResName'"
                      class="span-btn-ellipsis"
                    >
                      <span
                        v-show="row.firstResName"
                        class="span-btn-ellipsis-text"
                      >
                        {{ row[item.dataIndex] }}
                      </span>
                      <a
                        class="span-btn-ellipsis-btn"
                        @click="handleFirstResNameSelect(row)"
                      > {{ row.firstResName?'(重新选择)':'选择岗位' }} </a>
                    </span>

                    <!-- 第一责任人 -->
                    <!-- 直接责任人 -->
                    <div
                      v-if="item.dataIndex === 'directResPerList'"
                      class="span-btn-ellipsis"
                    >
                      <span
                        v-show="row.directResPerList && row.directResPerList.length>0 && !row.showSelect"
                        class="span-btn-ellipsis-text"
                      >
                        {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                      </span>
                      <a-select
                        v-show="row.showSelect"
                        :ref="'directSelect-' + row.sortNum"
                        v-model="row.directResPerList"
                        :placeholder="'请选择'+item.title"
                        label-in-value
                        mode="multiple"
                        class="span-btn-ellipsis-text"
                        @dropdownVisibleChange="dropdownVisibleChange($event, row)"
                        @change="((value)=>{handleDirectResPerList(value,row)})"
                      >
                        <a-select-option
                          v-for="{employeeId,name,phone} in directlyDutyPersonList"
                          :key="employeeId"
                          :value="employeeId"
                          :data="{directResPerName:name}"
                        >
                          <a-tooltip :placement="'topLeft'">
                            <template slot="title">
                              {{ phone }}
                            </template>
                            {{ name }}
                          </a-tooltip>
                        </a-select-option>
                      </a-select>
                      <a
                        class="span-btn-ellipsis-btn"
                        @click="handleDirectResPerSelect(row,true)"
                      >(点击选择)</a>
                    </div>

                    <!-- 直接责任人 -->
                    <!-- 是否为关键节点 -->
                    <a-switch
                      v-if="item.dataIndex === 'isKeyNode'"
                      v-model="row.isKeyNode"
                      checked-children="是"
                      un-checked-children="否"
                      @change="handleUpdate(row, false, item.dataIndex)"
                    />
                    <!-- 是否为关键节点 -->
                  </template>
                  <!-- 业务事项 -->
                </span>
                <!-- 编辑 -->
              </template>
            </u-table-column>
          </u-table>
        </a-spin>
      </a-card>
    </a-spin>
    <div
      v-if="!isConsultation"
      class="page-btn-right-top"
    >
      <!-- <div class="pub-next-btn page-btn-right-top"> -->
      <a-button
        v-if="!isDetail && !isAudit"
        type="primary"
        :loading="submiting"
        @click="handleSubmit('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="!isDetail && !isAudit"
        v-btnPermission="'pm_008_sub_03'"
        class="ml20"
        type="primary"
        :loading="submiting"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        class="ml20"
        @click="$close"
      >
        关闭
      </a-button>
    </div>
    <!-- 设置前置任务 -->
    <PredecessorTask
      :visible.sync="predecessorTaskVisible"
      :record="predecessorTaskRecord"
      :api="api"
      @changeFrontTask="changeFrontTask"
    />
    <!-- 设置前置任务 -->
    <!-- 选择第一责任人 -->
    <modal
      v-if="firstResNameVisible"
      :id="firstResNameData.id"
      :form-data="firstResNameData.formData"
      :org-query="firstResNameData.orgQuery"
      :screening="true"
      :visible="true"
      @handleCancelFirstRes="firstResNameVisible = false"
      @handleOk="handleFirstResName"
    />
    <!-- 选择第一责任人 -->
    <!-- 甘特图 -->
    <GanttModal
      :visible.sync="ganttVisible"
      :data="ganttData"
    />
    <!-- 甘特图 -->
    <!-- 导入模板 -->
    <TaskTemplateModal
      :select-level="selectLevel"
      :visible="taskTemplateVisible"
      @hide="importFromTemplateHide"
      @dataImport="onTemplateDataImport"
    />
    <!-- 导入模板 -->
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
    <!-- 选择审批人 -->
  </base-breadcrumb>
</template>
<script>
import { getProjects } from '@/api/construction/planInput'
import UploadList from '../progress/file'
import { columns1, controlLevelList, completeStandardList, verifyFilesList } from '../constructionSchedule/model.js'
import { view } from '@/api/construction/constructionCompleted'
import { UTable, UTableColumn } from 'umy-ui'
import PredecessorTask from '../constructionSchedule/components/PredecessorTask'
import modal from '@/components/SelectJobs'
import Vue from 'vue'
import GanttModal from '@/components/GanttModal'
import TaskTemplateModal from '../gantt/template-modal'
export default {
  name: 'constructionCompletedView' + Date.now(),
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  components: {
    UploadList,
    UTable,
    UTableColumn,
    PredecessorTask,
    modal,
    GanttModal,
    TaskTemplateModal
  },
  data() {
    return {
      // 前置接口
      api: view,
      // 代号网络图
      fileList: [],
      // 表头
      columns1: columns1.filter((el) => {
        const hide = ['dutySubUnit', 'isMilestonesNode', 'isMainProcessNode', 'isVerticalTransportNode','isContractDurationNode','contractStartDate','contractEndDate']
        if (!hide.includes(el.dataIndex)) {
          return el
        }
      }),
      // 选中项
      selectRow: {},
      // 表格加载
      loading: false,
      // 表格信息
      tableInfo: {
        projectName: void 0,
        nodeTotalNum: void 0,
        firstNodeNum: void 0,
        secondNodeNum: void 0,
        threeNodeNum: void 0,
        periodDay: void 0,
        periodDate: void 0
      },
      // 表格数据
      tableData: [],
      // 管控级别
      controlLevelList,
      // 完成标准
      completeStandardList,
      // 验证资料
      verifyFilesList,
      // 前置任务显示隐藏
      predecessorTaskVisible: false,
      // 前置任务行
      predecessorTaskRecord: {},
      // 第一责任人模态框显示隐藏
      firstResNameVisible: false,
      // 第一责任人模态框数据
      firstResNameData: {
        id: '',
        formData: {
          fileList: []
        },
        orgQuery: {},
        row: {}
      },
      // 直接责任人列表
      directlyDutyPersonList: [],
      // 提交
      submiting: false,
      // 是否隐藏显示上传文件
      showUpload: false,
      // 甘特图显示隐藏
      ganttVisible: false,
      // 甘特图数据
      ganttData: {
        list: [],
        lines: [],
        startDate: '',
        endDate: ''
      },
      selectLevel: '',
      // 导入模板显示隐藏
      taskTemplateVisible: false,
      // 项目id
      projectId: this.$route.query.projectId + '' || '',
      // 计划id
      scheduleCompletionPlanId: this.isAudit ? this.$route.query.businessId + '' : this.$route.query.scheduleCompletionPlanId + '',
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null,
      // 焦点值
      focusValue: {
        key: '',
        value: ''
      }
    }
  },
  computed: {
    // 没有选中
    notSelectRow() {
      return JSON.stringify(this.selectRow) === '{}'
    },
    // 是查看
    isDetail() {
      return this.$route.query.pageType === 'detail' || this.isAudit
    }
  },
  watch: {
    // 第一责任人模态框关闭
    // predecessorTaskVisible: {
    //   handler(newV, oldV) {
    //     if (!newV) {
    //       this.loadData()
    //     }
    //   }
    // },
    // 表格数据监听
    tableData: {
      handler(list) {
        if (this.$refs.table) {
          console.log('加载')
          // 扁平化树为甘特图数据
          let arr = []
          let lines = []
          const flatTree = (list) => {
            for (let i = 0; i < list.length; i++) {
              // 初始化时间弹层隐藏显示(解决时间输入识别后不能自动关闭)
              list[i].planStartTimeOpen = false
              list[i].planEndTimeOpen = false

              const obj = this.$clone(list[i])
              delete obj.childTree
              const { id: taskId, planStartTime: startDate, planEndTime: endDate, businessMatters, phaseCategory, statusLights, isKeyNode, nodeType } = obj
              const text = nodeType === 1 ? businessMatters : phaseCategory
              if (list[i].childTree) {
                flatTree(list[i].childTree)
              } else {
                obj.phaseCategory = text
                if (obj.frontConnectList && obj.frontConnectList.length > 0) {
                  lines = lines.concat(obj.frontConnectList)
                }
              }
              let color = ''
              const c = {
                0: 'class-slider-0',
                1: 'class-slider-1',
                2: 'class-slider-2',
                3: 'class-slider-3',
                4: 'class-slider-4'
              }
              // 甘特图颜色
              if (isKeyNode) {
                color = 'class-slider-key'
              } else if (this.$route.query.status + '' === '2') {
                color = c[statusLights]
              } else {
                color = 'class-slider-0'
              }
              arr.push({
                taskId,
                startDate,
                endDate,
                class: color,
                text,
                ...obj
              })
            }
          }
          flatTree(this.tableData)
          // 获取之前展开数据
          const expandRecords = this.$refs.table.getTreeExpandRecords()
          // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
          const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
          const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
          // 加载数据
          this.$refs.table.reloadData(list).then(() => {
            // 数据加载完成出现之后，打开之前的展开行
            expandRecords.forEach((row) => {
              this.$refs.table.setTreeExpansion(row, true)
            })
            // 还原之前滚动高度
            this.$refs.table.pagingScrollTopLeft(scrollTop + 1, scrollLeft)
            this.$nextTick(()=>{
              // 不加这一步，列表操作栏 会变形
              this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
            })
          })
          this.ganttData.list = arr.sort((a, b) => a.sortNum - b.sortNum)
          this.ganttData.lines = lines
        }
      }
    }
  },
  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('schedule_completion_plan')
  },
  mounted() {
    this.searchFiles()
    this.loadData()
    // 获取前置数据
    this.getProjects(this.projectId)
    const userInfo = Vue.getAcloudProvider().getUserInfo()
    this.firstResNameData.id = userInfo.id
  },
  methods: {
    /**
     * @description: 获取文件列表
     * @param {void}
     * @return {void}
     */
    searchFiles() {
      view.doubleNetworkPictureQuery(this.scheduleCompletionPlanId).then((res) => {
        if (res.code === 200) {
          this.fileList = res.data
        } else {
          this.fileList = []
        }
        if (this.fileList.length > 4) {
          this.showUpload = false
        } else {
          if (this.isAudit) {
            this.showUpload = false
          } else {
            this.showUpload = true
          }
        }
      })
    },
    /**
     * @description: 文件列表
     * @param {array} list
     * @return {void}
     */
    handleFileUploaded(list) {
      if (list.length > 4) {
        this.showUpload = false
      } else {
        this.showUpload = true
        this.fileList = [...list]
      }
    },
    /**
     * @description: 获取项目部信息
     * @param {string} id 项目id
     * @return {void}
     */
    getProjects(id) {
      if (!this.isDetail) {
        getProjects({ projectIds: [id] }).then((res) => {
          this.firstResNameData.orgQuery.ids = res.data[0].orgId
        })
      }
    },
    /**
     * @description: 表格数据加载方法
     * @param {boolean} isloading 是否显示加载
     * @return {Promise} 接口Promise
     */
    async loadData(isloading = true) {
      try {
        if (isloading) {
          this.loading = true
        }
        const {
          code,
          data: { projectName, nodeTotalNum, firstNodeNum, secondNodeNum, threeNodeNum, periodDay, planStartTime, planEndTime, treeListVO }
        } = await view.completionPlanDetail(this.scheduleCompletionPlanId)
        if (code === 200) {
          this.tableInfo = {
            projectName,
            nodeTotalNum,
            firstNodeNum,
            secondNodeNum,
            threeNodeNum,
            periodDay,
            periodDate: (planStartTime ?? '' !== '') && (planEndTime ?? '' !== '') ? planStartTime + '--' + planEndTime : '--'
          }
          this.tableData = treeListVO
          this.ganttData.startDate = planStartTime
          this.ganttData.endDate = planEndTime
        } else {
          this.tableData = []
        }
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      } finally {
        if (isloading) {
          this.loading = false
        }
      }
    },
    /**
     * @description: 获取直接责任人
     * @param {object} row 行数据
     * @return {void}
     */
    getDirectlyDutyPerson(row) {
      view.directlyDutyPersonSelectQuery({ nodeId: row.id, projectId: this.projectId }).then(({ code, data }) => {
        if (code === 200) {
          this.directlyDutyPersonList = data
        } else {
          this.directlyDutyPersonList = []
        }
      })
    },
    /**
     * @description: 表格行点击
     * @param {object} row 行数据
     * @param {object} column 表头对象
     * @param {event} event 事件对象
     * @return {void}
     */
    handleRowClick(row, column, event) {
      if (this.selectRow?.id === row.id) {
        // this.selectRow = {}
      } else {
        this.$set(this, 'selectRow', row)
        // 业务事项
        if (row.nodeType === 1) {
          this.getDirectlyDutyPerson(row)
        }
      }
    },
    /**
     * @description: 新增下级阶段/类别
     * @param {void}
     * @return {void}
     */
    handleCreateWorkPack() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增下级阶段/类别?',
        onOk() {
          view.createChildWorkPack({ selectedWorkPackId: vm.selectRow.id }).then(({ code }) => {
            if (code === 200) {
              vm.$message.success('新增成功')
              vm.loadData()
            }
          })
        }
      })
    },
    /**
     * @description: 新增同级阶段/类别
     * @param {void}
     * @return {void}
     */
    handleCreateSiblingWorkPack() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增同级阶段/类别?',
        onOk() {
          view.createSiblingWorkPack({ selectedWorkPackId: vm.selectRow.id }).then(({ code }) => {
            if (code === 200) {
              vm.$message.success('新增成功')
              vm.loadData()
            }
          })
        }
      })
    },
    /**
     * @description: 新增业务事项
     * @param {void}
     * @return {void}
     */
    handleCreateWork() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增业务事项?',
        onOk() {
          if (vm.selectRow.nodeType === 1) {
            // 新增同级业务事项
            view.siblingWork({ selectedWorkId: vm.selectRow.id }).then(({ code }) => {
              if (code === 200) {
                vm.$message.success('新增成功')
                vm.loadData()
              }
            })
          } else {
            // 新增下级业务事项
            view.createChildWork({ selectedWorkPackId: vm.selectRow.id }).then(({ code }) => {
              if (code === 200) {
                vm.$message.success('新增成功')
                vm.loadData()
              }
            })
          }
        }
      })
    },
    /**
     * @description: 上移
     * @param {void}
     * @return {void}
     */
    handleMoveUp() {
      view.moveUp({ selectedId: this.selectRow.id }).then(({ code }) => {
        if (code === 200) {
          this.$message.success('上移成功')
          this.loadData()
        }
      })
    },
    /**
     * @description: 下移
     * @param {void}
     * @return {void}
     */
    handleMoveDown() {
      view.moveDown({ selectedId: this.selectRow.id }).then(({ code }) => {
        if (code === 200) {
          this.$message.success('下移成功')
          this.loadData()
        }
      })
    },
    // /**
    //  * @description: 升级
    //  * @param {void}
    //  * @return {void}
    //  */
    // handleUpgradeWorkPack() {
    //   view.upgradeWorkPack({ selectedWorkPackId: this.selectRow.id }).then(({ code }) => {
    //     if (code === 200) {
    //       this.$message.success('升级成功')
    //       this.loadData()
    //     }
    //   })
    // },
    // /**
    //  * @description: 降级
    //  * @param {void}
    //  * @return {void}
    //  */
    // handleDowngradeWorkPack() {
    //   view.downgradeWorkPack({ selectedWorkPackId: this.selectRow.id }).then(({ code }) => {
    //     if (code === 200) {
    //       this.$message.success('降级成功')
    //       this.loadData()
    //     }
    //   })
    // },
    /**
     * @description: 格式化时间
     * @param {object/string} date 时间对象或字符串
     * @param {boolean} toMoment 是否转换为Moment
     * @return {object} moment时间格式
     */
    formatDate(date, toMoment = true) {
      if (date?._isAMomentObject) {
        return toMoment ? date : date.format('YYYY-MM-DD')
      } else {
        return toMoment ? this.moment(date) : date
      }
    },
    /**
     * @description: 计划开始时间禁用
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @return {boolean}
     */
    planStartTimeDisabled(current, row) {
      return row.planEndTime && current && current > this.moment(row.planEndTime).endOf('day')
    },
    /**
     * @description: 计划完成时间禁用
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @return {boolean}
     */
    planEndTimeDisabled(current, row) {
      return row.planStartTime && current && current < this.moment(row.planStartTime).startOf('day')
    },
    /**
     * @description: 计算周期
     * @param {object} row 行数据
     * @param {number} index 字段索引
     * @return {void}
     */
    handleComputePeriod(value, row, index) {
      const indexList = ['period', 'planStartTime', 'planEndTime']
      if ((value ?? '') === '') {
        if (index > 0) {
          // 日期格式提示
          this.$message.warning('请输入正确的日期格式，如“2023-01-01')
          return false
        } else {
          this.handleUpdate(row, false, indexList[index], true)
        }
      } else {
        const { period, planStartTime, planEndTime } = row
        // 长度不在有三个(取消周期)
        const length = [planStartTime, planEndTime].filter((el) => el ?? '' !== '').length
        // 时间周期值个等于2
        if (length === 2) {
          // 修改周期
          if (index === 0) {
            if ((period ?? '') !== '') {
              if ((planStartTime ?? '') !== '') {
                // 计算计划完成时间
                row.planEndTime = this.formatDate(planStartTime).clone().add(period, 'days')
              } else {
                // 计算计划开始时间
                row.planStartTime = this.formatDate(planEndTime).clone().subtract(period, 'days')
              }
            }
          }
          // 修改计划开始时间
          if (index === 1) {
            if ((planStartTime ?? '') !== '') {
              if ((planEndTime ?? '') !== '') {
                // 计算周期
                row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
              } else {
                // 计算计划完成时间
                row.planEndTime = this.formatDate(planStartTime).clone().add(period, 'days')
              }
            }
          }
          // 修改计划完成时间
          if (index === 2) {
            if ((planEndTime ?? '') !== '') {
              if ((planStartTime ?? '') !== '') {
                // 计算周期
                row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
              } else {
                // 计算计划开始时间
                row.planStartTime = this.formatDate(planEndTime).clone().subtract(period, 'days')
              }
            }
          }
        }
        // 时间周期值个等于3
        if (length === 3) {
          // 修改周期或者修改计划开始时间
          if (index === 0 || index === 1) {
            // 计算计划完成时间
            row.planEndTime = this.formatDate(planStartTime).clone().add(period, 'days')
          }
          // 修改计划完成时间
          if (index === 2) {
            // 计算周期
            row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
          }
        }
        // 结合open、openChange解决时间选择器不能在输入后自动关闭的问题
        if (index === 1 || index === 2 || index === 3 || index === 4) {
          row.planStartTimeOpen = false
          row.planEndTimeOpen = false
        }
        this.handleUpdate(row, false, indexList[index], true)
      }
    },
    /**
     * @description: 完成标准带出验证资料
     * @param {string} value 完成标准值
     * @param {object} row 行数据
     * @return {void}
     */
    handleCompleteStandard(value, row) {
      const index = this.completeStandardList.findIndex((el) => el === value)
      if (index >= 0) {
        row.verifyFiles = this.verifyFilesList[index]
      }
      this.handleUpdate(row, false, 'completeStandard')
    },
    /**
     * @description: 直接责任人下拉展开收起
     * @param {*} visible
     * @param {*} row
     * @return {*}
     */
    dropdownVisibleChange(visible, row) {
      if (!visible) {
        this.handleDirectResPerSelect(row, false)
      }
    },
    /**
     * @description: 直接责任人改变
     * @param {object} value 选中项
     * @param {object} row 行数据
     * @return {void}
     */
    handleDirectResPerList(value, row) {
      row.directResPerList = this.directlyDutyPersonList
        .filter((item) => value.map((el) => el.key).includes(item.employeeId))
        .map((el) => {
          return {
            key: el.employeeId,
            label: el.name
          }
        })
      this.handleUpdate(row, false, 'directResPerList')
    },
    /**
     * @description: 直接责任人选择
     * @param {object} row 行数据
     * @return {void}
     */
    handleDirectResPerSelect(row, isShow) {
      this.$set(row, 'showSelect', isShow)
      if (row.showSelect) {
        this.$refs[`directSelect-${row.sortNum}`][0].$el.click()
      }
    },
    /**
     * @description: 递归查找修改阶段/类别
     * @param {array} list
     * @param {string} id
     * @param {string} phaseCategory
     * @return {void}
     */
    updatePhaseCategory(list, id, phaseCategory) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === id) {
          list[i].phaseCategory = phaseCategory
          return false
        }
        if (Array.isArray(list[i].childTree) && list[i].childTree.length > 0) {
          this.updatePhaseCategory(list[i].childTree, id, phaseCategory)
        }
      }
    },
    /**
     * @description: 焦点值
     * @param {string} key 字段名
     * @param {string} value 字段值
     * @return {void}
     */
    saveFocusValue(key, value) {
      this.focusValue = {
        key,
        value
      }
    },
    /**
     * @description: 编辑
     * @param {object} row 行数据
     * @param {boolean} refresh 需要刷新
     * @param {string} blurIndex 失焦字段
     * @return {void}
     */
    async handleUpdate(row, refresh = false, blurIndex = '') {
      if (row.nodeType === 0) {
        // 编辑阶段/类别

        // 失去焦点时值未改变
        if (this.focusValue.key === blurIndex) {
          // 时间格式
          if (row[blurIndex]?._isAMomentObject) {
            if (row[blurIndex].format('YYYY-MM-DD') === (this.focusValue.value?._isAMomentObject ? this.focusValue.value?.format('YYYY-MM-DD') : this.focusValue.value)) return
          } else {
            if (this.focusValue.value === row[blurIndex]) return
          }
        }

        const { id, phaseCategory: name, parentId } = row
        this.updatePhaseCategory(this.tableData, id, name)
        // this.tableData = [...this.tableData]
        await view.editWorkPack({ id, name, parentId })
      } else {
        // 编辑业务事项

        if (blurIndex !== '') {
          // 失去焦点

          // 失去焦点时值未改变
          if (this.focusValue.key === blurIndex) {
            // 时间格式
            if (row[blurIndex]?._isAMomentObject) {
              if (row[blurIndex].format('YYYY-MM-DD') === (this.focusValue.value?._isAMomentObject ? this.focusValue.value?.format('YYYY-MM-DD') : this.focusValue.value)) return
            } else {
              if (this.focusValue.value === row[blurIndex]) return
            }
          }
        } else {
          // 其他情况loading
          this.loading = true
        }
        const { id, businessMatters: name, parentId: workPackId, controlLevelId, period, planStartTime, planEndTime, completeStandard, verifyFiles, isKeyNode, firstResId, firstResName, directResPerList } = row
        const { code } = await view.editWork({
          id,
          name,
          workPackId,
          controlLevelId,
          period,
          planStartTime: this.formatDate(planStartTime, false),
          planEndTime: this.formatDate(planEndTime, false),
          completeStandard,
          verifyFiles,
          isKeyNode,
          firstResId,
          firstResName,
          directResPerList
        })
        this.loading = false
        if (code !== 200) {
          this.$message.warning('编辑失败')
          if (refresh) {
            this.loadData()
          }
        } else {
          // 刷新表格
          if (refresh) {
            this.loadData()
            this.selectRow = {}
          }
        }
      }
    },
    /**
     * @description: 删除
     * @param {void}
     * @return {void}
     */
    handleRemove() {
      const vm = this
      if (this.selectRow.nodeType === 0) {
        // 删除阶段/类别
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定删除阶段/类别?',
          onOk() {
            view.removeWorkPack({ selectedWorkPackId: vm.selectRow.id }).then(({ code }) => {
              if (code === 200) {
                vm.$message.success('删除成功')
                vm.loadData()
              }
            })
          }
        })
      } else {
        // 删除业务事项
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定删除业务事项?',
          onOk() {
            view.removeWork({ selectedWorkId: vm.selectRow.id }).then(({ code }) => {
              if (code === 200) {
                vm.$message.success('删除成功')
                vm.loadData()
              }
            })
          }
        })
      }
    },
    /**
     * @description: 设置前置任务
     * @param {object} row 当前行数据
     * @return {void}
     */
    handlePredecessorTask(row) {
      this.predecessorTaskVisible = true
      this.predecessorTaskRecord = row
      this.focusValue = {
        key: 'frontTask',
        value: row.frontTask
      }
    },
    /**
     * @description: 前置任务改变
     * @param {array} data 前置任务表数据
     * @return {void}
     */
    changeFrontTask(data) {
      const list = data.filter((el) => !el.update)
      this.predecessorTaskRecord.frontTask = list.map((el) => el.sortNum + el.nodeType).join()
      this.predecessorTaskRecord.intervalTime = list.map((el) => el.intervalDay).join()
    },
    /**
     * @description: 选择第一责任人
     * @param {object} row 当前行数据
     * @return {void}
     */
    handleFirstResNameSelect(row) {
      this.firstResNameData.row = row
      this.firstResNameVisible = true
    },
    /**
     * @description: 选择第一责任人回调
     * @param {object} value 选中项数据
     * @return {void}
     */
    handleFirstResName(value) {
      this.firstResNameData.row.firstResId = value.jobsSelectedId
      this.firstResNameData.row.firstResName = value.jobsSelectedName
      this.firstResNameVisible = false
      this.handleUpdate(this.firstResNameData.row, false, 'firstResName')
    },
    /**
     * @description: 跳转节点信息
     * @param {number} level 节点等级
     * @return {void}
     */
    handleNodeInfo(level) {
      if (this.isDetail && !this.isAudit) {
        this.$router.push({
          path: '/construction/constructionSchedule/implementationManagement/nodeInfo',
          query: {
            level,
            projectId: this.projectId
          }
        })
      }
    },
    /**
     * @description: 提交
     * @param {string} planStatus 操作类型
     * @return {void}
     */
    handleSubmit(planStatus = 'SUBMITTED') {
      if (planStatus === 'SUBMITTED') {
        if (this.fileList.length === 0) {
          this.$message.warning('请上传双代号网络图')
        } else {
          const vm = this
          // this.$confirm({
          //   title: '提交确认',
          //   content: '请确认是否要提交？',
          //   onOk() {
          vm.submitfun(planStatus)
          // }
          // })
        }
      } else {
        this.submitfun(planStatus)
      }
    },
    /**
     * @description: 提交函数
     * @param {string} planStatus 操作类型
     * @return {void}
     */
    submitfun(planStatus) {
      this.setProcessConfig = null
      this.submitApprovalConfirm(planStatus == 'SUBMITTED' ? this.processConfig : 6, (flag) => {
        if (!flag) return
        this.submiting = true
        view
          .completionPlanSubmitApproval({ scheduleCompletionPlanId: this.scheduleCompletionPlanId + '', planStatus })
          .then(({ code, data }) => {
            if (code === 200) {
              this.$message.success('操作成功！')
              // 提交成功后关闭页面
              if (planStatus === 'SUBMITTED') {
                this.businessId = data
                this.setProcessConfig = this.processConfig
              }
            }
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.submiting = false
          })
      })
    },
    /**
     * @description: 隐藏导入模板
     * @param {void}
     * @return {void}
     */
    importFromTemplateHide() {
      this.taskTemplateVisible = false
    },
    /**
     * @description: 导入模板
     * @param {*} dataList
     * @param {*} selectedTemplate
     * @param {*} selectedStartDate
     * @return {*}
     */
    onTemplateDataImport(dataList, selectedTemplate, selectedStartDate) {
      const data = {
        children: dataList,
        id: this.selectRow.id,
        planId: this.scheduleCompletionPlanId + '',
        parentId: this.selectRow.parentId,
        startDate: selectedStartDate,
        templateId: selectedTemplate,
        type: 1
      }
      view
        .importTemplate(data)
        .then((res) => {
          if (res.code == 200 || res.data.code == 200) {
            this.$message.success('导入成功')
            this.loadData()
          }
        })
        .catch(() => {
          this.progressingTips = ''
          this.progressing = false
        })
    },
    /**
     * @description: 展开全部
     * @return {void}
     */
    allTreeExpansion(){
      if(!this.isAudit && !this.isDetail){
        this.loadData()
      }
      this.$refs.table.setAllTreeExpansion()
    }
  }
}
</script>
<style lang="less">
.row-active {
  background-color: #e6f7ff;
}
</style>
<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .plTableBox .el-table td {
  padding: 3px 0;
  height: 40px !important;
}
@{deep} .plTableBox .el-table th {
  padding: 8px 0;
}
.btn-wrapper {
  margin: 0 -5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  > button {
    margin: 3px;
  }
}
.pub-table-select-count {
  margin-top: 5px;
  > span {
    margin-right: 12px;
  }
}
.width-100 {
  width: 100%;
}
@{deep} .construction-schedule-view-table .el-table td .cell {
  overflow: visible;
}
.span-ellipsis {
  width: 100%;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.span-btn-ellipsis {
  width: 100%;
  display: flex;
  justify-content: center;
}
.span-btn-ellipsis-text {
  width: calc(100% - 85px);
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.span-btn-ellipsis-btn {
  width: 75px;
  margin-left: 10px;
}
</style>
